package com.wwy.arithmetic.suanfa;

import org.springframework.util.CollectionUtils;
import sun.awt.image.ImageWatched;

import java.util.*;
import java.util.stream.Stream;

/**
 * @author 王伟羽
 * @program: arithmetictest
 * @description: 不重复的最长字符串
 * @create: 2024/07/05
 */

public class NoRepetitionString {


    public static void main(String[] args) {
        String a = "aabaab!bb";
        Integer num = test(a);
        System.out.println("num = " + num);
    }

    static Integer getRepetitionString(String s) {
        int n = s.length();
        if (n <= 1) {
            return n;
        }
        int l = 0, r = 1;
        HashSet<Character> set = new HashSet<>();
        set.add(s.charAt(l));
        int res = 0;
        while (r < n) {
            while (r < n && !set.contains(s.charAt(r))) {
                set.add(s.charAt(r));
                r++;
            }
            res = Math.max(res, r - l);
            set.remove(s.charAt(l));
            l++;
        }
        return res;
    }

    static int test(String s) {
        int n = s.length();
        if (n <= 1) {
            return n;
        }
        int max = 0;
        char[] chars = s.toCharArray();
        Set<Character> set = new HashSet<>();
        StringBuilder sb = new StringBuilder();
        Deque<Character> deque = new LinkedList<>();
        Map<Character, Integer> map = new HashMap<>();
        //计数器
        int a = 0;
        for (int i = 0; i < chars.length; i++) {
            if (set.add(chars[i])) {
                a++;
                sb.append(chars[i]);
                deque.push(chars[i]);
                map.put(chars[i], i);
            } else {
                max = Math.max(a,max);
                while (!deque.isEmpty()) {
                    Character pop = deque.pollLast();
                    set.remove(pop);
                    if (pop.equals(chars[i])) {
                        Integer integer = map.get(chars[i]);
                        sb.replace(0,integer,"");
                        a = i-integer;
                        map.put(chars[i],i);
                        set.add(chars[i]);
                        deque.push(chars[i]);
                        break;
                    }
                }
            }
        }
        max = Math.max(a,max);
        return max;
    }

}
